<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>	
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.concurrent.locks.Lock"%>
<%@page import="java.util.concurrent.locks.ReentrantLock"%>

<%
	// Struts2  请求 包装过滤器
	MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
	// 获得上传的文件名 
	String fileName = wrapper.getFileNames("imgFile")[0];
	File file = wrapper.getFiles("imgFile")[0];
	
	// 文件保存硬盘路径
	String savePath = pageContext.getServletContext().getRealPath("/") + "upload/";
	// 文件保存相对路径
	String saveUrl  = request.getContextPath() + "/upload/";
	String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
	// 最大文件大小
	long maxSize = 1000000;
	
	response.setContentType("text/html; charset=UTF-8");
	
	// 检查目录
	File uploadDir = new File(savePath);
	if(!uploadDir.isDirectory()){
		out.println(getError("上传目录不存在!"));
		return;
	}
	// 检查目录写权限
	if(!uploadDir.canWrite()){
		out.println(getError("上传目录没有写权限!"));
		return;
	}
	
	// 检查文件大小
	if(file.length() > maxSize){
		out.println(getError("上传文件大小超过限制!"));
		return;
	}
	
	// 检查扩展名
	String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
	if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
		out.println(getError("上传文件扩展名不符合系统要求!"));
		return;
	}
	
	final Lock lock = new ReentrantLock();
	String newName = null;
	lock.lock();
	try {
		// 加锁为防止文件名重复 
		newName = System.currentTimeMillis()
				+ fileName.substring(fileName.lastIndexOf("."),
						fileName.length());
	}finally {
		lock.unlock();
	}
	
	FileOutputStream fos = new FileOutputStream(request.getSession()
			.getServletContext().getRealPath("/")
			+ "upload\\" + newName);
	
	byte[] buffer = new byte[1024];
	// 获取内存中当前文件输入流 
	InputStream in = new FileInputStream(file);
	try {
		int num = 0;
		while ((num = in.read(buffer)) > 0) {
			fos.write(buffer, 0, num);
		}
	} catch (Exception e) {
		e.printStackTrace(System.err);
	} finally {
		in.close();
		fos.flush();
		fos.close();
	}
	
	JSONObject obj = new JSONObject();
	obj.put("error", 0);
	obj.put("url", saveUrl + newName);
	out.println(obj.toJSONString());
%>
<%!
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
%>